/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package smtp;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Hashtable;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.naming.*;
import javax.naming.directory.*;

/**
 *
 * @author lailiaidi
 */
public class SMTPLookup {
    /*recheck the result in here http://www.fixyourip.com/resolve_dns.php */

    private Attribute attr;
    private String obStrMailAddress;

    public SMTPLookup(String obStrMailAddress) {
        this.obStrMailAddress = obStrMailAddress;
        this.attr = null;
    }

    /* This method validate the obStrMailAddress address template */
    //http://www.devx.com/tips/Tip/28334
    //http://haacked.com/archive/2007/08/21/i-knew-how-to-validate-an-obStrMailAddress-address-until-i.aspx
    public boolean isValidEmail() {
        boolean isValid = false;
        Pattern p = Pattern.compile("^[a-z][a-z0-9_]*@[a-z][a-z0-9_]{1,}\\.[a-z][a-z0-9_]{1,}$");
        //".+@.+\\.[a-z]+"
        //("[.&[^@]] @[.&[^@]] \\.[a-z]{2,}");
        //"^[a-z][a-z0-9_]*@[a-z][a-z0-9_]{1,}\\.[a-z][a-z0-9_]{1,}$"
        //^(?!\.)("([^"\r\\]|\\["\r\\])*"|([-a-z0-9!#$%&'*+/=?^_`{|}~] |(?@[a-z0-9][\w\.-]*[a-z0-9]\.[a-z][a-z\.]*[a-z]$

        // Match the given string with the pattern
        Matcher m = p.matcher(obStrMailAddress);

        // check whether match is found
        boolean matchFound = m.matches();

        StringTokenizer st = new StringTokenizer(obStrMailAddress, ".");
        String lastToken = null;
        while (st.hasMoreTokens()) {
            lastToken = st.nextToken();
        }
        /* validate the country code */
        if (matchFound && lastToken.length() >= 2 && obStrMailAddress.length() - 1 != lastToken.length()) {
            /* If receiver the obStrMailAddress addres is not valid, output the error to client */
            isValid = true;
        }
        return isValid;
    }

    /*
    http://www.rgagnon.com/javadetails/java-0452.html
    Perform a DNS lookup for MX records in the domain
     */
    public String getSMTPServerHostName() {
        String obStrSMTPServerHostName = "";
        if (obStrMailAddress.contains("@")) {
            obStrSMTPServerHostName = obStrMailAddress.substring(obStrMailAddress.indexOf("@") + 1);
        }
        if (obStrSMTPServerHostName.contains("<")) {
            obStrSMTPServerHostName = obStrSMTPServerHostName.replaceAll("<", "");
        }
        if (obStrSMTPServerHostName.contains(">")) {
            obStrSMTPServerHostName = obStrSMTPServerHostName.replaceAll(">", "");
        }
        if (obStrSMTPServerHostName.length() > 0) {
            Hashtable env = new Hashtable();
            env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
            try {

                DirContext ictx = new InitialDirContext(env);
                Attributes attrs = ictx.getAttributes(obStrSMTPServerHostName, new String[]{"MX"});
                Attribute attr = attrs.get("MX");
                if (attr != null) {
                    obStrSMTPServerHostName = (((String) attr.get(0)).split(" "))[1];
                } else {
                    obStrSMTPServerHostName = null;//The email address doesn't have valid SMTP server
                }
            } catch (NamingException ne) {
                System.out.println("Failed to get server name");
                obStrSMTPServerHostName = null;//The email address doesn have valid SMTP server
            }
        }
        return obStrSMTPServerHostName;
    }

    //http://www.java2s.com/Code/Java/Network-Protocol/ConvertahostnametotheequivalentIPaddress.htm
    public String getSMTPServerAddress(String SMTPServerHostName) {
        String obStrSMTPServerAddress = "";
        InetAddress address = null;
        try {
            address = InetAddress.getByName(SMTPServerHostName);
            obStrSMTPServerAddress = address.getHostAddress();
        } catch (UnknownHostException e) {
            System.out.println("Failed to get server address");
            obStrSMTPServerAddress = null;
        }
        return obStrSMTPServerAddress;
    }
}
